package cn.codexin.wechatofficial.interceptor;

import cn.codexin.wechatofficial.service.UserInfoService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private UserInfoService userInfoService;

    @Value("${wechat.app-id}")
    private String appId;

    @Value("${wechat.server-url}")
    private String serverUrl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("get header,openid: " + request.getHeader("openid"));
        String openid = request.getHeader("openid");
        if (userInfoService.isRegister(openid)) {
            //已注册，检查是否审批
            if (userInfoService.isChecked(openid)) {
                log.info("已审批");
                return true;
            }
            log.info("待审批");
            setReturn(response, false, "待审批");
        } else {
            //未注册
            log.info("未注册");
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                    "appid=" + appId + "&redirect_uri=" + serverUrl +
                    "&response_type=code&scope=snsapi_base&state=base#wechat_redirect";
//            response.sendRedirect(url);
            setReturn(response, false, url);
        }
        return false;
    }

    //返回错误信息
    private static void setReturn(HttpServletResponse response, boolean state, String msg) throws IOException {
        //UTF-8编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> map = new HashMap<>();
        map.put("state", state);
        map.put("msg", msg);
        String json = JSON.toJSONString(map);
        response.getWriter().print(json);
    }

}
